package com.zhuky.shiro;

import com.zhuky.entity.SysUser;
import com.zhuky.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Shiro 认证和授权的核心类
 * @author zhu
 */
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;


    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUser user = (SysUser)principals.fromRealm(this.getClass().getName()).iterator().next();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRole("admin");
        return authorizationInfo;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken)token;
        String loginName = upToken.getUsername();
        SysUser user = sysUserService.selectByLoginName(loginName);
        return new SimpleAuthenticationInfo(user,user.getPassword(),this.getClass().getName());
    }
}
